package com.haojiang.mh

import android.app.Activity
import android.app.Application
import android.bluetooth.BluetoothAdapter
import android.content.Context
import android.content.IntentFilter
import android.net.wifi.WifiManager
import androidx.appcompat.app.AppCompatDelegate
import androidx.multidex.MultiDex
import cn.com.heaton.blelibrary.ble.Ble
import cn.com.heaton.blelibrary.ble.BleLog
import cn.com.heaton.blelibrary.ble.model.BleDevice
import cn.com.heaton.blelibrary.ble.model.BleFactory
import cn.com.heaton.blelibrary.ble.utils.UuidUtils
import cn.com.superLei.aoparms.AopArms
import com.clj.fastble.BleManager
import com.clj.fastble.scan.BleScanRuleConfig
import com.haojiang.mh.cache.Const
import com.haojiang.mh.remote.bean.BleRssiDevice
import com.haojiang.mh.remote.utils.MyBleWrapperCallback
import com.haojiang.mh.service.BluetoothOffReceiver
import com.haojiang.mh.service.WiFiScanResultReceiver
import com.haojiang.mh.service.api.TokenInterceptor
import com.haojiang.mh.utils.MUtil
import com.haojiang.mh.utils.SpUtil
import com.lzy.okgo.OkGo
import com.lzy.okgo.cookie.CookieJarImpl
import com.lzy.okgo.cookie.store.SPCookieStore
import com.lzy.okgo.interceptor.HttpLoggingInterceptor
import com.lzy.okgo.model.HttpHeaders
import com.tencent.bugly.crashreport.CrashReport
import me.jessyan.autosize.AutoSize
import me.jessyan.autosize.AutoSizeConfig
import me.jessyan.autosize.onAdaptListener
import me.jessyan.autosize.utils.AutoSizeLog
import okhttp3.OkHttpClient
import java.util.*
import java.util.concurrent.TimeUnit
import java.util.logging.Level

/**
 * Application
 *
 * Created by ZapFive on 2019-05-25.
 *
 * wuzhuang@mirahome.me
 */
class AppContext : Application() {

    var name: String = ""

    companion object {
        private var instance: AppContext? = null
        fun instance() = instance!!
    }

    override fun attachBaseContext(base: Context?) {
        super.attachBaseContext(base)
        MultiDex.install(this)      //开启多个dex文件支持
    }

    override fun onCreate() {
        super.onCreate()
        instance = this
        initKotlin()
        initJava()
    }

    private fun initKotlin() {
        //SharedPreferences初始化
        SpUtil.sp = getSharedPreferences("hj_bed_sp.pref", Context.MODE_PRIVATE)

        //矢量图支持
        AppCompatDelegate.setCompatVectorFromResourcesEnabled(true)

        //OkGo初始化
        initOkGo()

        //BleManager初始化
        initBle()

        //Bugly
        CrashReport.initCrashReport(this, "08ed164519", false)

        //WiFi离线广播
        val netReceiver = WiFiScanResultReceiver()
        val netFilter = IntentFilter()
        netFilter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)
        registerReceiver(netReceiver, netFilter)

        //蓝牙关闭广播
        val bleReceiver = BluetoothOffReceiver()
        val bleFilter = IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED)
        registerReceiver(bleReceiver, bleFilter)

        initServer()
    }

    private fun initJava() {
        AppJava(this)
    }

    private fun initBle() {
        val bleManager = BleManager.getInstance()
        bleManager.init(this)
        bleManager.enableLog(BuildConfig.LOG_DEBUG)
        bleManager.setReConnectCount(1, 5000)
        bleManager.operateTimeout = 5000
        val rule = BleScanRuleConfig.Builder()
        rule.setDeviceName(true, Const.DEVICE_PREFIX)
        rule.setScanTimeOut(10_000L)
        bleManager.initScanRule(rule.build())
    }

    private fun initOkGo() {
        val builder = OkHttpClient.Builder()
        //超时时间设置
        builder.readTimeout(10_000L, TimeUnit.MILLISECONDS)
        builder.writeTimeout(10_000L, TimeUnit.MILLISECONDS)
        builder.connectTimeout(5_000L, TimeUnit.MILLISECONDS)
        //自动管理cookie
        builder.cookieJar(CookieJarImpl(SPCookieStore(this)))
        //Log相关
        val logInterceptor = HttpLoggingInterceptor("AiBuy")
        if (BuildConfig.LOG_DEBUG) {
            logInterceptor.setPrintLevel(HttpLoggingInterceptor.Level.BODY)
        } else {
            logInterceptor.setPrintLevel(HttpLoggingInterceptor.Level.NONE)
        }
        logInterceptor.setColorLevel(Level.INFO)
        builder.addInterceptor(logInterceptor)
        //公共头
        val params = HttpHeaders()
        params.put("user-agent-custom", MUtil.getUserAgent())
        //token参数
        builder.addInterceptor(TokenInterceptor())

        val okGo = OkGo.getInstance().init(this)
        okGo.okHttpClient = builder.build()
        okGo.retryCount = 0
        okGo.addCommonHeaders(params)
    }



    private fun initServer() {
        name = SpUtil.get("server", ServerEnum.CHINA.name)
        when (name) {
            ServerEnum.CHINA.name -> {
                Const.server = ServerEnum.CHINA.url
            }
            ServerEnum.AMERICA.name -> {
                Const.server =  ServerEnum.AMERICA.url
            }
            ServerEnum.GERMANY.name -> {
                Const.server =  ServerEnum.GERMANY.url
            }
        }
    }

}